package com.bocai.kelalacar.ui.car.main.act;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bocai.kelalacar.R;
import com.bocai.kelalacar.base.BaseActivity;
import com.bocai.kelalacar.bean.MyAddressBean;
import com.bocai.kelalacar.util.DBManager;
import com.bocai.kelalacar.util.DateUtil;
import com.bocai.kelalacar.widget.CarNumDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yuanfei on 2017/6/6.
 * 筛选页面
 */

public class SelectActivity extends BaseActivity {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.img_right)
    ImageView imgRight;
    @BindView(R.id.btn_success)
    Button btnSuccess;
    @BindView(R.id.ll_service)
    LinearLayout llService;
    @BindView(R.id.ll_toolbar_share)
    LinearLayout llToolbarShare;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.ll_select_date)
    LinearLayout llSelectDate;
//    @BindView(R.id.tv_car_num)
//    TextView tvCarNum;
    @BindView(R.id.tv_start_address)
    TextView tvStartAddress;
    @BindView(R.id.ll_start_address)
    LinearLayout llStartAddress;
    @BindView(R.id.tv_end_address)
    TextView tvEndAddress;
    @BindView(R.id.ll_end_address)
    LinearLayout llEndAddress;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    private DBManager dbM;
    private SQLiteDatabase db;
    public List<MyAddressBean> options1Items = new ArrayList<>();
    public List<List<MyAddressBean>> options2Items = new ArrayList<>();
    private OptionsPickerView<MyAddressBean> mPvOptions;
    private String startCityId, endCityId,originCityName,arriveCityName;
    private int index = 0;
    TimePickerView pickerView;
    String startTime;

    @Override
    public int getLayoutId() {
        return R.layout.activity_select;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        initToolbar("筛选");
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        new positionAsyn().execute();
        setDataView();
    }

    @OnClick({R.id.ll_start_address,R.id.ll_end_address,R.id.btn_confirm,R.id.ll_select_date})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.ll_start_address:
                index = 1;
                if (mPvOptions != null) {
                    mPvOptions.show();
                } else {
                    showShortToast("正在加载地址选项");
                }
                break;
            case R.id.ll_end_address:
                index = 2;
                if (mPvOptions != null) {
                    mPvOptions.show();
                } else {
                    showShortToast("正在加载地址选项");
                }
                break;
            case R.id.ll_select_date:
                pickerView.show();
                break;
            case R.id.btn_confirm:
                Intent intent = new Intent(SelectActivity.this,MainListActivity.class);
                intent.putExtra("time",startTime);
                intent.putExtra("time1",tvData.getText().toString());
//                intent.putExtra("seats",tvCarNum.getText().toString());
                intent.putExtra("originCity",startCityId);
                intent.putExtra("arriveCity",endCityId);
                intent.putExtra("originCityName",originCityName);
                intent.putExtra("arriveCityName",arriveCityName);
                startActivity(intent);
                break;
        }
    }
    public void setDataView() {
        pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                tvData.setText(DateUtil.dateToDateTimeString(date));
                startTime = DateUtil.getMonth(date)+"月"+DateUtil.getDays(date)+"日";

                if (!TextUtils.isEmpty(startCityId)&&!TextUtils.isEmpty(endCityId)
                        &&!TextUtils.isEmpty(tvData.getText().toString())){
                    btnConfirm.setEnabled(true);
                    btnConfirm.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnConfirm.setEnabled(false);
                    btnConfirm.setTextColor(getResources().getColor(R.color.text_color));
                }

            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                .build();
    }

    public void setAddressSelect() {

        if (options1Items.size() <= 0 || options2Items.size() <= 0) {
            options1Items.clear();
            options2Items.clear();
            db = dbM.openDatabase();
            options1Items = findProvince();
            for (MyAddressBean entity : options1Items) {
                List<MyAddressBean> list = findCityOrArea(entity);
                if (list.size() > 0) {
                    options2Items.add(list);
                } else {
                    list.add(new MyAddressBean("", "", ""));
                    options2Items.add(list);
                }

            }
        }

    }

    private ArrayList<MyAddressBean> findProvince() {
        ArrayList<MyAddressBean> provice = new ArrayList<>();

        Cursor cursor = db.rawQuery("SELECT * FROM bnt_districts WHERE ParentId = ?", new String[]{"0"});
        while (cursor.moveToNext()) {
            MyAddressBean entity = new MyAddressBean(cursor.getString(cursor.getColumnIndex("Id")),
                    cursor.getString(cursor.getColumnIndex("ParentId")),
                    cursor.getString(cursor.getColumnIndex("FullName")));

            provice.add(entity);
        }
        cursor.close();
        return provice;
    }


    public OptionsPickerView initPickView() {
        //选项选择器
        OptionsPickerView<MyAddressBean> pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (index == 1) {
                    startCityId = options2Items.get(options1).get(options2).getId();
                    originCityName =options2Items.get(options1).get(options2).getFullName();
                    tvStartAddress.setText(options1Items.get(options1).getFullName()+" "+options2Items.get(options1).get(options2).getFullName());
                } else if (index == 2) {
                    endCityId = options2Items.get(options1).get(options2).getId();
                    arriveCityName =options2Items.get(options1).get(options2).getFullName();
                    tvEndAddress.setText(options1Items.get(options1).getFullName()+" "+options2Items.get(options1).get(options2).getFullName());
                }
                if (!TextUtils.isEmpty(startCityId)&&!TextUtils.isEmpty(endCityId)
                        &&!TextUtils.isEmpty(tvData.getText().toString())){
                    btnConfirm.setEnabled(true);
                    btnConfirm.setTextColor(getResources().getColor(R.color.color_white));
                }else {
                    btnConfirm.setEnabled(false);
                    btnConfirm.setTextColor(getResources().getColor(R.color.text_color));
                }

            }
        }).build();
        //三级联动效果
        pvOptions.setPicker(options1Items, options2Items);
        //设置选择的三级单位
        pvOptions.setSelectOptions(0, 0);

        return pvOptions;

    }

    private ArrayList<MyAddressBean> findCityOrArea(MyAddressBean bean) {
        ArrayList<MyAddressBean> citys = new ArrayList<>();
        Cursor cursor = db.rawQuery("SELECT * FROM bnt_districts WHERE ParentId = ?", new String[]{bean.getId()});
        while (cursor.moveToNext()) {
            MyAddressBean entity = null;
            entity = new MyAddressBean(cursor.getString(cursor.getColumnIndex("Id")),
                    cursor.getString(cursor.getColumnIndex("ParentId")),
                    cursor.getString(cursor.getColumnIndex("FullName")));

            citys.add(entity);
        }
        cursor.close();
        return citys;
    }

    public class positionAsyn extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
//            showDialog("正在加载");
//            startProgressDialog("正在加载");
        }

        @Override
        protected String doInBackground(String... strings) {
            dbM = new DBManager(SelectActivity.this);
            setAddressSelect();
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
//            stopProgressDialog();
            mPvOptions = initPickView();
        }
    }

}
